package com.dux.commons.configuration.transformers;

import java.lang.reflect.Field;
import java.net.InetAddress;
import java.net.InetSocketAddress;

import com.dux.commons.configuration.PropertyTransformer;
import com.dux.commons.configuration.TransformationException;



/**
 * 字符串转换成InetSocketAddress类型
 * @author 杜祥
 * @create 2013-6-29
 */
public class InetSocketAddressTransformer implements PropertyTransformer<InetSocketAddress>
{

	
	public static final InetSocketAddressTransformer	SHARED_INSTANCE	= new InetSocketAddressTransformer();


	
	@Override
	public InetSocketAddress transform(String value, Field field) throws TransformationException
	{
		String[] parts = value.split(":");

		if(parts.length != 2)
		{
			throw new TransformationException("Can't transform property, must be in format \"address:port\"");
		}

		try
		{
			if("*".equals(parts[0]))
			{
				return new InetSocketAddress(Integer.parseInt(parts[1]));
			}
			else
			{
				InetAddress address = InetAddress.getByName(parts[0]);
				int port = Integer.parseInt(parts[1]);
				return new InetSocketAddress(address, port);
			}
		}
		catch(Exception e)
		{
			throw new TransformationException(e);
		}
	}
}
